<template>
  <div class="login-container">
    <el-form
      ref="loginForm"
      :model="form"
      :rules="rules"
      class="login-form"
      label-width="80px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="form.username"
          prefix-icon="el-icon-user"
          placeholder="请输入用户名"
        />
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input
          v-model="form.password"
          type="password"
          prefix-icon="el-icon-lock"
          placeholder="请输入密码"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleLogin" :loading="isLoading">
          登录
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { postLogin } from "@/api";

export default {
  data() {
    return {
      form: {
        username: "",
        password: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, message: "密码至少6位", trigger: "blur" },
        ],
      },
      isLoading: false,
    };
  },
  methods: {
    async handleLogin() {
      this.$refs.loginForm.validate(async (valid) => {
        if (!valid) return;

        this.isLoading = true;
        try {
          const res = await postLogin(this.form);
          if (res.data.status === 0) {
            this.$message.success(res.data.message || "登录成功! ");
            // 存储 token
            localStorage.setItem("token", res.data.token);
            this.$store.commit("setToken", res.data.token);
            // 存储用户信息
            this.$store.commit("setUser", res.data.user);
            // 设置登录状态为 true
            this.$store.commit("setIsLogin", true);
            // 登录成功后跳转（根据实际路由配置修改）
            const redirect = this.$route.query.redirect || "/";
            this.$router.push(redirect);
          } else {
            this.$message.error(res.message || "登录失败! ");
          }
        } catch (err) {
          this.$message.error("网络请求失败");
        } finally {
          this.isLoading = false;
        }
      });
    },
  },
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f0f2f5;
}

.login-form {
  width: 350px;
  padding: 30px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>
